package com.wkg.lotterysystem.service.activitystatus.operater;

import com.wkg.lotterysystem.dao.dataobject.ActivityDo;
import com.wkg.lotterysystem.dao.mapper.ActivityMapper;
import com.wkg.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.wkg.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.wkg.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.wkg.lotterysystem.service.enums.ActivityStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ActivityOperator extends AbstractActivityOperator {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    /**
     * 是否状态需要转换
     *
     * @param convertActivityStatusDTO 这是从MQ中获取到的数据
     * @return
     */
    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        Integer activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetStatus = convertActivityStatusDTO.getTargetActivityStatus();

        if (null == activityId
                || null == targetStatus) {
            return false;
        }
        ActivityDo activityDo = activityMapper.selectById(activityId);
        if (null == activityDo) {
            return false;
        }

        //当前状态是否与传入的状态是否一致,一致不处理
        if (targetStatus.name().equalsIgnoreCase(activityDo.getStatus())) {
            return false;
        }

        //需要判断奖品是否全部抽完
        //查询INIY状态的奖品个数
        //这是重点,需要根据activityid与活动关联的奖品奖状太进行查询是否还有未被抽取的奖品
        int count = activityPrizeMapper.countPrize(activityId, ActivityPrizeStatusEnum.INIT.name());
        if (count > 0) {
            return false;
        }
        return true;
    }

    /**
     * 状态转换
     *
     * @param activityStatusDTO
     * @return
     */
    @Override
    public Boolean convert(ConvertActivityStatusDTO activityStatusDTO) {
        try {
            activityMapper.updateStatus(activityStatusDTO.getActivityId(),
                    activityStatusDTO.getTargetActivityStatus().name());
            return true;
        } catch (Exception e) {
            return false;
        }

    }
}
